package com.hemaapp.yjnh.activity;

import java.util.ArrayList;

import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.view.District;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CmnBookProductionAdapter;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.AdImage;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.view.ImageCarouselBanner;

/**乐乐
 * @author GuiyouZhang
 * Date：2015年12月21日 下午3:20:34
 * Email:guiyouzhang@163.com
 */
public class LeleActivity extends BaseActivity implements OnClickListener{

	private static final int REQUEST_CITY = 0x01;
	
	private LinearLayout layout_title;//整个title的布局
	private ImageButton titleLeftBtn;
	private ImageView titleSearch;
	private TextView tvCity;
	private RefreshLoadmoreLayout layoutRefresh;
	private XtomListView listview;

	private View headerView;
	private ImageCarouselBanner imageCarouselBanner;
	private LinearLayout layoutLocal;
	private LinearLayout layoutAround;
	private TextView leleHot;
	private TextView leleSuperValues;
	private TextView tvArea;

	private ArrayList<AdImage> imgs = new ArrayList<AdImage>();
	private ArrayList<Blog> mBlogs = new ArrayList<Blog>();//推荐的乐乐商品
	private CmnBookProductionAdapter mAdapter;
	private String city;//当前选择的城市
    private int curPage = 0;
    private String provinceId = "0";//地级市所在的省份id
    private String province;//当前选择的城市
    private String provinceName = "";//地级市所在的省份名称
	private String lat = "";//纬度
    private String lng = "";//经度
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_lele);
		super.onCreate(savedInstanceState);
		//2016.10.31 start 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
//		province = XtomSharedPreferencesUtil.get(mContext, "province");
//		city = XtomSharedPreferencesUtil.get(mContext, "city");
        province = XtomSharedPreferencesUtil.get(mContext, "province_lele");
        city = XtomSharedPreferencesUtil.get(mContext, "city_lele");
        if (isNull(province) || isNull(city)) {
            province = XtomSharedPreferencesUtil.get(mContext, "province");
            city = XtomSharedPreferencesUtil.get(mContext, "city");
        }
		//2016.10.31 end 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
		lat = XtomSharedPreferencesUtil.get(mContext, "lat");
		lng = XtomSharedPreferencesUtil.get(mContext, "lng");
		init();
	}
	
	private void init() {
		headerView = LayoutInflater.from(mContext).inflate(R.layout.header_lele, null);
		findHeaderViews();
		listview.addHeaderView(headerView);
		//获取广告图片列表
//		getNetWorker().ModelADList("1", city.substring(0, city.length()-1));
		getNetWorker().ModelADList("1", city);
		if (!isNull(province)) {
		    getNetWorker().districtList(provinceId);//获取所有的城市
        }else
            XtomToastUtil.showShortToast(mContext, "获取位置信息失败");
	}

	/**获取图片列表
	 * 
	 */
	private void getImageList() {
		getNetWorker().ModelADList("1", city);
	}

	/**获取商品列表
	 * 
	 */
	private void getGoods() {
		getNetWorker().blogList("9", city, "1", "1", "", "", "", "", "", 
				"", lng, lat, "", "", curPage+"");
	}

	private void findHeaderViews() {
        imageCarouselBanner = (ImageCarouselBanner) headerView.findViewById(R.id.image_carousel_banner);

		layoutLocal = (LinearLayout) headerView.findViewById( R.id.layout_local );
		layoutAround = (LinearLayout) headerView.findViewById( R.id.layout_around );
		leleHot = (TextView) headerView.findViewById( R.id.tv_hot );
		leleSuperValues = (TextView) headerView.findViewById( R.id.tv_overvalue );
		tvArea = (TextView) headerView.findViewById( R.id.tv_area );
		if (!isNull(city)) {
			tvCity.setText(city);
			tvArea.setText(city+"周边");
		}

		layoutLocal.setOnClickListener( this );
		layoutAround.setOnClickListener( this );
		leleHot.setOnClickListener( this );
		leleSuperValues.setOnClickListener( this );
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_btn:
			layout_title.setVisibility(View.GONE);
			finish();
			break;
		case R.id.tv_city:
			Intent itProvince = new Intent(mContext, CityActivity.class);
			itProvince.putExtra("type", 1);
			itProvince.putExtra("parent_id", "-1");
			startActivityForResult(itProvince, REQUEST_CITY);
			break;
		case R.id.title_right_img:
			Intent itSearch = new Intent(mContext, SearchActivity.class);
			itSearch.putExtra("type", 9);
			itSearch.putExtra("assort", "乐乐");
			startActivity(itSearch);
			break;
		case R.id.layout_local:
			Intent it = new Intent(mContext, CmnProductionListWithDistrictActivity.class);
			it.putExtra("keytype", "9");
			it.putExtra("keyid", city);
			it.putExtra("keyword", "");
			it.putExtra("saleflag", "");
			it.putExtra("topflag", "");
			it.putExtra("cheapflag", "");
			it.putExtra("score_percent", "");
			it.putExtra("seller_id", "");
			it.putExtra("district_name", "");
			mContext.startActivity(it);
			break;
		case R.id.layout_around:
			Intent itAround = new Intent(mContext, CmnProductionListWithDistrictActivity.class);
			itAround.putExtra("provinceId", provinceId);
            itAround.putExtra("keytype", "9");
            itAround.putExtra("keyid", provinceName);
            itAround.putExtra("keyword", "");
            itAround.putExtra("saleflag", "");
            itAround.putExtra("topflag", "");
            itAround.putExtra("cheapflag", "");
            itAround.putExtra("score_percent", "");
            itAround.putExtra("seller_id", "");
            itAround.putExtra("district_name", "");
            startActivity(itAround);
			break;
		case R.id.tv_hot:
			Intent itHot = new Intent(mContext, CmnProductionListWithDistrictActivity.class);
            itHot.putExtra("keytype", "9");
            itHot.putExtra("keyid", city);
            itHot.putExtra("keyword", "");
            itHot.putExtra("saleflag", "");
            itHot.putExtra("topflag", "1");
            itHot.putExtra("cheapflag", "");
            itHot.putExtra("score_percent", "");
            itHot.putExtra("seller_id", "");
            itHot.putExtra("district_name", "");
            startActivity(itHot);
			break;
		case R.id.tv_overvalue:
			Intent itSuper = new Intent(mContext, CmnProductionListWithDistrictActivity.class);
            itSuper.putExtra("keytype", "9");
            itSuper.putExtra("keyid", city);
            itSuper.putExtra("keyword", "");
            itSuper.putExtra("saleflag", "");
            itSuper.putExtra("topflag", "");
            itSuper.putExtra("cheapflag", "1");
            itSuper.putExtra("score_percent", "");
            itSuper.putExtra("seller_id", "");
            itSuper.putExtra("district_name", "");
            startActivity(itSuper);
			break;
		default:
			break;
		}
	}


	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case MODELAD_LIST:
		case BLOG_LIST:
		case CLIENT_LIST:
        case DISTRICT_LIST:
			showProgressDialog("加载中");
		default:
			break;
		}
		super.callBeforeDataBack(netTask);
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case MODELAD_LIST:
		case BLOG_LIST:
		case CLIENT_LIST:
        case DISTRICT_LIST:
			cancelProgressDialog();
		default:
			break;
		}
		super.callAfterDataBack(netTask);
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case MODELAD_LIST:
			HemaPageArrayResult<AdImage> aResult = (HemaPageArrayResult<AdImage>) baseResult;
			if (aResult == null || aResult.getObjects() == null)
				return;
			if (imgs == null) {
				imgs = new ArrayList<AdImage>();
			} else {
				imgs.clear();
			}
			imgs.addAll(aResult.getObjects());
			initPager();
            curPage = 0;
			getGoods();
			break;
		case BLOG_LIST:
			HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
			if (bResult == null || bResult.getObjects() == null)
				return;
			if (curPage == 0) {// 刷新
				layoutRefresh.refreshSuccess();
				mBlogs.clear();
				mBlogs.addAll(bResult.getObjects());
			}else {
				layoutRefresh.loadmoreSuccess();
				if (bResult.getObjects().size()>0) {
					mBlogs.addAll(bResult.getObjects());
				}else {
					layoutRefresh.setLoadmoreable(false);
					XtomToastUtil.showShortToast(mContext, "已经到最后啦");
				}
			}
			refreshData(-1);
			break;
        case DISTRICT_LIST:
            HemaPageArrayResult<District> dResult = (HemaPageArrayResult<District>) baseResult;
            if (dResult == null || dResult.getObjects() == null) {
                return;
            }
            ArrayList<District> districts = dResult.getObjects();
            for(District district:districts) {
                if (province.substring(0, 2).equals(district.getName().substring(0, 2))) {
                    provinceId = district.getId();
                    String[] parentNames = district.getNamepath().split(",");
                    provinceName = parentNames[0];
                    break;
                }
            }
            break;
		default:
			break;
		}
		super.callBackForServerSuccess(netTask, baseResult);
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case MODELAD_LIST:
		case BLOG_LIST:
			if (curPage == 0) {// 刷新
				layoutRefresh.refreshFailed();
			}else {
				layoutRefresh.loadmoreFailed();
			}
            XtomToastUtil.showShortToast(mContext, "操作失败，"+baseResult.getMsg());
			break;
        case DISTRICT_LIST:
            XtomToastUtil.showShortToast(mContext, "获取位置信息失败，"+baseResult.getMsg());
            break;
		default:
			break;
		}
		super.callBackForServerFailed(netTask, baseResult);
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case MODELAD_LIST:
		case BLOG_LIST:
			if (curPage == 0) {// 刷新
				layoutRefresh.refreshFailed();
			}else {
				layoutRefresh.loadmoreFailed();
			}
            XtomToastUtil.showShortToast(mContext, "操作失败，请稍后再试");
			break;
        case DISTRICT_LIST:
            XtomToastUtil.showShortToast(mContext, "获取位置信息失败");
            break;
		default:
			break;
		}
		super.callBackForGetDataFailed(netTask, failedType);
	}
	
	private void refreshData(int failedType) {
		if (mAdapter == null) {
			mAdapter = new CmnBookProductionAdapter(mContext, mBlogs);
            mAdapter.setClickListener(new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = new Intent(mContext, BookProductionDetailActivity.class);
                    it.putExtra("blog_id", mBlogs.get(position).getId());
                    startActivity(it);
                }
            });
			mAdapter.setEmptyString("暂时没有推荐");
			listview.setAdapter(mAdapter);
		}else {
			mAdapter.setEmptyString("暂时没有推荐");
			mAdapter.notifyDataSetChanged();
		}
		mAdapter.setFailtype(failedType);
	}

	@Override
	protected void findView() {
		layoutRefresh = (RefreshLoadmoreLayout)findViewById( R.id.layout_refresh );
		listview = (XtomListView)findViewById( R.id.listview );
		layout_title = (LinearLayout) findViewById(R.id.layout_title);
		titleLeftBtn = (ImageButton) findViewById( R.id.title_left_btn );
		tvCity = (TextView) findViewById( R.id.tv_city );
		titleSearch = (ImageView) findViewById(R.id.title_right_img);
		super.findView();
	}

	@Override
	protected void setListener() {
		titleLeftBtn.setOnClickListener( this );
		tvCity.setOnClickListener( this );
        layoutRefresh.setOnStartListener(new StartListener());
		titleSearch.setOnClickListener(this);
		super.setListener();
	}

	private class StartListener implements OnStartListener {

		@Override
		public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
			curPage = 0;
			getImageList();
		}

		@Override
		public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
			curPage++;
			getImageList();
		}
	}
	
	private void initPager() {
		ArrayList<String> urls = new ArrayList<>();
		for (AdImage item : imgs) {
			urls.add(item.getImgurl());
		}
		imageCarouselBanner.getLayoutParams().height = XtomWindowSize.getWidth(mContext)/2;
		imageCarouselBanner.onInstance(mContext, urls, R.drawable.ad_show_indicator,
				new ImageCarouselHeadClickListener(mContext, imgs, "2"));
	} 

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (RESULT_OK != resultCode) {
			return;
		}
		switch (requestCode) {
		case REQUEST_CITY:
			if (data == null) {
				return;
			}
			provinceId = data.getStringExtra("parentId");
			provinceName = data.getStringExtra("parentName");
			city = getCityName();
			tvCity.setText(city);
            tvArea.setText(city+"周边");
	        getImageList();
	        getNetWorker().districtList(provinceId);//获取所有的城市
            //2016.10.31 start 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
            XtomSharedPreferencesUtil.save(mContext, "province_lele", provinceName);
            XtomSharedPreferencesUtil.save(mContext, "city_lele", city);
            //2016.10.31 end 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
